package cn.yeziji.file.handler.channel;

import cn.yeziji.file.basic.MinioProperties;
import cn.yeziji.file.handler.service.TypeSelected;
import cn.yeziji.file.service.FileService;
import cn.yeziji.file.service.InteractionService;
import cn.yeziji.forum.common.AliCloudOss;
import cn.yeziji.forum.basic.file.WebUploader;
import cn.yeziji.forum.basic.file.WebUploaderFileEntity;
import cn.yeziji.forum.utils.AliUtils;
import cn.yeziji.forum.utils.SpringUtils;
import cn.yeziji.forum.utils.entity.AliOssConfig;
import cn.yzj.common.CommonSymbol;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文档操作
 *
 * @author gzkemays
 * @since 2022/11/03 11:38 PM
 */
@Slf4j
public class DocsHandler extends FileTypeHandler {
  MinioProperties properties;
  AliCloudOss oss;
  InteractionService interactionService;
  FileService fileService;

  public DocsHandler(TypeSelected selected) {
    super(selected);
    this.properties = SpringUtils.getBean(MinioProperties.class);
    this.oss = SpringUtils.getBean(AliCloudOss.class);
    this.interactionService = SpringUtils.getBean(InteractionService.class);
    this.fileService = SpringUtils.getBean(FileService.class);
  }

  @Override
  public void handler(WebUploader.ChuckEntity entity) {
    // 如果是 pdf 此处返回省略图地址
    Object types = typeHandler.types(TypeSelected.PDF);
    String entityPath = entity.getPath();
    String filename = entity.getOriginalFilename();
    log.info("types => " + types);
    if (entityPath.equals(TypeSelected.DOCS_PATH)) {
      // 省略图上传成功
      Integer chunks = entity.getChunks();
      String path = entity.getPath(), username = entity.getUsername();
      String desc = entity.getDesc();
      Long size = entity.getSize();
      String scope = path + "/" + filename + CommonSymbol.STAR_SIGN + chunks;
      // 上传文件
      String thumbUrl = String.valueOf(types);
      String filePath = properties.getSavePath() + File.separator + filename;
      Path streamPath = Paths.get(filePath);
      // 其他文档类型
      String fileUrl;
      log.info("开始上传文件");
      try {
        fileUrl =
            AliUtils.uploadToOss(
                AliOssConfig.cloudOss(oss)
                    .savePath(TypeSelected.DOCS_PATH)
                    .fileName(filename)
                    .stream(Files.newInputStream(streamPath))
                    .build());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      log.info("上传文件完毕 -> {}", fileUrl);
      // 删除本地文件
      log.info("删除文件 —> {}", filePath);
      try {
        Files.delete(streamPath);
        log.info("删除文件完毕");
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      interactionService.save(
          new WebUploaderFileEntity(scope, fileUrl, username, desc, size, thumbUrl));
    }
  }
}
